package org.my.workflow.element;

import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.my.workflow.Interceptor;
import org.my.workflow.WorkflowException;
import org.w3c.dom.Element;

/**
 * @author <a href="mailto:yang_y@sysnet.com.cn">Young Yang</a>
 */
public class InterceptorElement implements ConfigElement {
    private String className;
    private Map<String, String> args = new HashMap<String, String>();

    private Interceptor interceptor = null;

    public Interceptor getInterceptor() {
        if (interceptor == null) {
            try {
                Class interceptorClass = this.getClass().getClassLoader().loadClass(className);
                if(Interceptor.class.isAssignableFrom(interceptorClass)){
                    Class<? extends Interceptor> _conditionClass = interceptorClass.asSubclass(Interceptor.class);
                    interceptor = _conditionClass.newInstance();
                }
                else {
                    throw new WorkflowException("Invalid interceptor class: " + className + ", must implements " + Interceptor.class.getName());
                }
            }
            catch (Exception e) {
                throw new WorkflowException("Instantiate Interceptor with class name: " + className + " failed.", e);
            }
        }
        return interceptor;
    }

    public Map<String, String> getArgs() {
        return Collections.unmodifiableMap(args);
    }

    public void processXML(Element element) {
        this.className = XMLUtils.getAtrributeValue(element, "classname");
        List<Element> argElements = XMLUtils.getChildElementsByTagName(element, "arg");
        for (Element argElement : argElements) {
            String name = XMLUtils.getAtrributeValue(argElement, "name");
            String value = XMLUtils.getNodeValue(argElement);
            args.put(name, value);
        }
    }

    public String toString() {
        return super.toString() + "[classname=" + className + ", args=" + args + "]";
    }
}
